export default {
    namespaced: true,
    state: {
      cartData: [],
    },
    mutations: {
      SET_CART(state, payload) {
        let target = state.cartData.find((item) => item.id === payload.id);
        if (!target) {
          let obj = {
            id: payload.id,
            title: payload.title,
            price: payload.price,
            inventory: payload.inventory,
            count: 1,
          };
          state.cartData.push(obj);
        } else {
          target.count++;
        }
      },
      CLS_CART(state, payload) {
        let target = state.cartData.find((item) => item.id === payload.id);
        target.count--;
        if (target.count < 1) {
          state.cartData = state.cartData.filter(
            (item) => item.id !== payload.id
          );
        }
      },
    },
    actions: {
      ADD_CART(context, payload) {
        context.commit("SET_CART", payload);
        context.commit("products/DECREASE_INVENTORY", payload, { root: true });
      },
      RM_CART(context, payload) {
        context.commit("CLS_CART", payload);
        context.commit("products/INCREASE_INVENTORY", payload, { root: true });
      },
    },
    getters: {
      total(state) {
        return state.cartData
          .reduce((total, item) => {
            return (total += item.price * item.count);
          }, 0)
          .toFixed(2);
      },
    },
  };
  